<template>
    <div class="container">
        <div class="move flex" :style="{transform: chatShow ? 'translateX(-100vw)' : 'translateX(0)'}">
            <div class="main flex fd-column relative">
                <div class="header flex ai-center">
                    <div class="profile" :style="{
                        backgroundImage: `url(${userData.profile.url})`,
                        backgroundSize: userData.profile.scale / 50 * 40 + 'px',
                        backgroundPosition: `${userData.profile.pos.x / 50 * 40}px ${userData.profile.pos.y / 50 * 40}px`,
                    }"></div>
                    <div class="userData f1 flex fd-column jc-end">
                        <div class="name">{{userData.username}}</div>
                        <div class="signature">{{userData.signature}}</div>
                    </div>
                    <div class="friendReq relative flex jc-center ai-center" @click="reqShow = true">
                        <i class="iconfont icon-plus"></i>
                        <div class="notification" v-show="userData.friendReq.length > 0"></div>
                    </div>
                </div>
                <div class="search relative">
                    <label>
                        <input type="text" placeholder="搜索" @keyup="search">
                    </label>
                    <div v-show="searchShow || reqShow" class="return">
                        <div class="box flex ai-center" @click="panelHide">
                            <i class="iconfont icon-angle-down"></i>
                            <p>返回</p>
                        </div>
                    </div>
                </div>
                <div class="content f1 flex" :style="{transform: navTri ? 'translateX(-100vw)' : 'translateX(0)'}">
                    <div class="currentMessage">
                        <p class="notice" v-if="userData.currentMessages.length === 0">您还没有和他人进行过会话</p>
                        <ul @click="toChat">
                            <li class="relative hidden"
                                v-for="item in userData.currentMessages" :key="item._id"
                            >
                                <div class="item relative flex ai-center">
                                    <div class="profile" :style="{
                                        backgroundImage: `url(${item.opposite.profile.url})`,
                                        backgroundSize: item.opposite.profile.scale + 'px',
                                        backgroundPosition: `${item.opposite.profile.pos.x}px ${item.opposite.profile.pos.y}px`,
                                    }"></div>
                                    <div class="data f1">
                                        <div class="up flex">
                                            <p class="name">{{item.opposite.username}}</p>
                                            <p class="time">{{item.content.mList[item.content.mList.length - 1].time.slice(16, 21)}}</p>
                                        </div>
                                        <div class="massage flex">
                                            <p class="f1">{{item.content.mList[item.content.mList.length - 1].text}}</p>
                                            <div class="notification" v-show="item.unread !== 0">{{item.unread}}</div>
                                        </div>
                                    </div>
                                    <div class="clickTarget" :data-uid="item.opposite._id"></div>
                                </div>
                                <div class="delete flex jc-center ai-center">删除</div>
                            </li>
                        </ul>
                    </div>
                    <div class="friends">
                        <ul>
                            <li>
                                <div class="group flex ai-center" @click="friendsShow = !friendsShow">
                                    <i class="iconfont icon-angle-right" :style="{transform: `rotate(${friendsShow ? '90' : '0'}deg)`}"></i>
                                    <p class="name f1">我的好友</p>
                                    <span class="num">{{online}}/{{userData.friends.length}}</span>
                                </div>
                                <ul v-show="friendsShow" @click="toChat">
                                    <li class="item relative flex ai-center" v-for="item in userData.friends" :key="item._id">
                                        <div class="profile" :style="{
                                            backgroundImage: `url(${item.profile.url})`,
                                            backgroundSize: item.profile.scale + 'px',
                                            backgroundPosition: `${item.profile.pos.x}px ${item.profile.pos.y}px`,
                                        }"></div>
                                        <div class="userData f1">
                                            <p class="name">{{item.username}}</p>
                                            <div class="signature">{{item.signature}}</div>
                                        </div>
                                        <div class="clickTarget" :data-uid="item._id"></div>
                                    </li>
                                </ul>
                            </li>
                        </ul>
                    </div>
                    <div class="searchPanel" v-show="searchShow" :style="{left: navTri ? '100vw' : '0'}">
                        <div class="tips">搜索成功 {{searchTips}}</div>
                        <div class="returnValue flex" v-if="searchUser">
                            <div class="profile" :style="{
                                backgroundImage: `url(${searchUser.profile.url})`,
                                backgroundSize: searchUser.profile.scale + 'px',
                                backgroundPosition: `${searchUser.profile.pos.x}px ${searchUser.profile.pos.y}px`,
                            }"></div>
                            <div class="data f1">
                                <p class="name">{{searchUser.username}}</p>
                                <div class="signature">{{searchUser.signature}}</div>
                            </div>
                            <a class="add" v-show="canAdd" :style="{pointerEvents: hasAdd ? 'none' : 'auto', color: hasAdd ? '#999' : '#888'}" @click="sendFriReq">{{hasAdd ? '已添加' : '添加'}}</a>
                        </div>
                    </div>
                    <div class="reqPanel" v-show="reqShow" :style="{left: navTri ? '100vw' : '0'}">
                        <p class="tips" v-show="userData.friendReq.length === 0">暂时还没有人添加你为好友</p>
                        <ul>
                            <li class="returnValue flex" v-for="req in userData.friendReq" :key="req._id">
                                <div class="profile" :style="{
                                    backgroundImage: `url(${req.profile.url})`,
                                    backgroundSize: req.profile.scale + 'px',
                                    backgroundPosition: `${req.profile.pos.x}px ${req.profile.pos.y}px`,
                                }"></div>
                                <div class="data f1">
                                    <p class="name">{{req.username}}</p>
                                    <div class="signature">{{req.signature}}</div>
                                </div>
                                <a class="add" @click="agreeFriReq(req._id)">添加</a>
                                <a class="reject" @click="rejectFriReq(req._id)">拒绝</a>
                            </li>
                        </ul>
                    </div>
                </div>
                <div class="nav flex">
                    <div class="currentMessage" @click="navTri = false">消息</div>
                    <div class="friends" @click="navTri = true">好友</div>
                </div>
            </div>
            <div class="chat relative flex fd-column">
                <div class="header flex ai-center">
                    <div class="back" @click="exitChat">
                        <i class="iconfont icon-angle-down"></i>
                    </div>
                    <div class="name f1">{{chatTarget.username}}</div>
                    <div class="more relative">
                        <i class="iconfont icon-more" @click.stop="delChatBtn = !delChatBtn"></i>
                        <div class="delete" v-show="delChatBtn" @click="deleteChat">删除聊天</div>
                    </div>
                </div>
                <div class="content f1" ref="mList">
                    <ul class="relative"
                        :style="{transform: `translateY(${dragHeight}px)`}"
                        @touchstart="checkTop"
                        @touchmove="mListMove"
                        @touchend="loadMore"
                    >
                        <li class="loadingPanel flex jc-center">
                            <div class="loadBox flex jc-center ai-center" :class="{'play': isLoad}">
                                <i class="iconfont icon-loading play"></i>
                            </div>
                        </li>
                        <li class="flex" v-for="message in chatMessages" :key="message._id" :class="{'userSite': message.poster === userData.username}">
                            <div class="profile" v-if="message.poster === userData.username" :style="{
                                backgroundImage: `url(${userData.profile.url})`,
                                backgroundSize: userData.profile.scale / 50 * 40 + 'px',
                                backgroundPosition: `${userData.profile.pos.x / 50 * 40}px ${userData.profile.pos.y / 50 * 40}px`,
                            }"></div>
                            <div class="profile" v-else :style="{
                                backgroundImage: `url(${chatTarget.profile.url})`,
                                backgroundSize: chatTarget.profile.scale / 50 * 40 + 'px',
                                backgroundPosition: `${chatTarget.profile.pos.x / 50 * 40}px ${chatTarget.profile.pos.y / 50 * 40}px`,
                            }"></div>
                            <div class="info">
                                <p class="name" v-if="message.poster !== userData.username">{{message.poster}}</p>
                                <p class="message" :class="{'img': message.textType === 'img'}" v-html="message.preText"></p>
                            </div>
                        </li>
                    </ul>
                </div>
                <div class="input flex ai-end" :class="`h${inputBoxHeight}`">
                    <div class="text f1">
                        <label>
                            <textarea v-model="text" @focus="updateMListScroll" @blur="updateMListScroll" @input="textChange"></textarea>
                            <textarea class="fakeInput" ref="fakeInput"></textarea>
                        </label>
                    </div>
                    <div class="other flex ai-center">
                        <div class="emoji" @click.stop="showEmoji">
                            <i class="iconfont icon-smile"></i>
                        </div>
                        <div class="more" v-show="text === ''" @click.stop="showMore">
                            <i class="iconfont icon-plus"></i>
                        </div>
                        <a class="send" v-show="text !== ''" @click="postMessage">发送</a>
                    </div>
                </div>
                <div class="moreBox">
                    <div class="emojiList flex" v-show="emojiShow" @click.stop="addEmoji">
                        <div>
                            <i class="iconfont icon-smile" title="smile"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-angry" title="angry"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-dizzy" title="dizzy"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-flushed" title="flushed"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-frown" title="frown"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-frown-open" title="frown-open"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-grimace" title="grimace"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-grin" title="grin"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-grin-alt" title="grin-alt"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-grin-beam" title="grin-beam"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-grin-hearts" title="grin-hearts"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-grin-beam-sweat" title="grin-beam-sweat"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-grin-squint" title="grin-squint"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-grin-squint-tears" title="grin-squint-tears"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-grin-stars" title="grin-stars"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-grin-tears" title="grin-tears"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-grin-tongue" title="grin-tongue"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-grin-tongue-squint" title="grin-tongue-squint"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-grin-wink" title="grin-wink"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-grin-tongue-wink" title="grin-tongue-wink"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-kiss" title="kiss"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-kiss-beam" title="kiss-beam"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-kiss-wink-heart" title="kiss-wink-heart"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-laugh" title="laugh"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-laugh-beam" title="laugh-beam"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-laugh-squint" title="laugh-squint"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-laugh-wink" title="laugh-wink"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-meh" title="meh"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-meh-blank" title="meh-blank"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-meh-rolling-eyes" title="meh-rolling-eyes"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-sad-cry" title="sad-cry"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-sad-tear" title="sad-tear"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-smile-beam" title="smile-beam"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-smile-wink" title="smile-wink"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-surprise" title="surprise"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-tired" title="tired"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-hand-lizard" title="hand-lizard"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-hand-peace" title="hand-peace"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-hand-point-down" title="hand-point-down"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-hand-point-left" title="hand-point-left"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-hand-point-right" title="hand-point-right"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-hand-point-up" title="hand-point-up"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-hand-rock" title="hand-rock"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-hand-scissors" title="hand-scissors"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-hand-paper" title="hand-paper"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-handshake" title="handshake"></i>
                        </div>
                        <div>
                            <i class="iconfont icon-heart" title="heart"></i>
                        </div>
                    </div>
                    <div class="more flex" v-show="moreShow" @click.stop>
                        <div class="box relative flex jc-center">
                            <i class="iconfont icon-image flex jc-center ai-center"></i>
                            <label>
                                <input type="file" accept="image/*" @change="postImage">
                            </label>
                        </div>
                    </div>
                </div>
                <img-look :src="viewImgSrc"
                          :alt="viewImgAlt"
                          :show="viewShow"
                          ref="imgLook"
                          @close="closeViewer"
                ></img-look>
<!--                <div class="pictureView flex jc-center ai-center"-->
<!--                     v-show="viewShow"-->
<!--                     @touchend="closeViewer"-->
<!--                >-->
<!--                    <img :src="viewImgSrc" :alt="viewImgAlt">-->
<!--                </div>-->
            </div>
        </div>
    </div>
</template>

<script>
    import imgLook from '../components/mobile/imgLook';

    export default {
        name: "mobile",
        components: {
            'img-look': imgLook
        },
        data() {
            return {
                socket: null,

                userData: {
                    username: '',
                    signature: '',
                    profile: {
                        pos: {
                            x: 0,
                            y: 0,
                        },
                        scale: '0',
                        url: ''
                    },
                    friendReq: [],
                    friends: [],
                    currentMessages: [],
                },

                navTri: false,

                //搜索内容与界面
                searchShow: false,
                searchTips: '',
                searchUser: null,
                canAdd: false,
                hasAdd: false,

                //消息界面
                tmFlag: false,

                reqShow: false,

                friendsShow: false,
                online: 0,

                chatShow: false,

                //拖动加载
                canDrag: false,
                dragFlag: false,
                dragStartPageY: 0,
                dragHeight: 0,
                isLoad: false,
                listHeight: 0,
                //是否有拖动 点击查看图片用
                hasMoveList: false,

                //chat part
                delChatBtn: false,
                inputBoxHeight: 1,
                chatTarget: {
                    username: '',
                },
                chatMessages: [],
                totalLength: 0,
                mLimit: 15,
                messageID: '',
                text: '',
                //用来进行textarea自适应
                textScrollHeight: 34,

                // more
                emojiShow: false,
                emojiList: [
                    'smile', 'angry', 'dizzy', 'flushed', 'frown',
                    'frown-open', 'grimace', 'grin', 'grin-alt', 'grin-beam',
                    'grin-hearts', 'grin-beam-sweat', 'grin-squint', 'grin-squint-tears', 'grin-stars',
                    'grin-tears', 'grin-tongue', 'grin-tongue-squint', 'grin-wink', 'grin-tongue-wink',
                    'kiss', 'kiss-beam', 'kiss-wink-heart', 'laugh', 'laugh-beam',
                    'laugh-squint', 'laugh-wink', 'meh', 'meh-blank', 'meh-rolling-eyes',
                    'sad-cry', 'sad-tear', 'smile-beam', 'smile-wink', 'surprise',
                    'tired', 'hand-lizard', 'hand-peace', 'hand-point-down', 'hand-point-left',
                    'hand-point-right', 'hand-point-up', 'hand-rock', 'hand-scissors', 'hand-paper',
                    'handshake', 'heart',
                ],
                moreShow: false,

                // 查看图片
                viewShow: false,
                viewImgSrc: '',
                viewImgAlt: ''
            }
        },
        methods: {
            init(data) {
                let {user, online} = data;
                if (!user) {
                    alert('用户不存在');
                    this.$router.replace('/login');
                }
                this.userData = user;
                this.online = online;
            },

            updateOnline(data) {
                this.online += data.num;
            },

            async search(e) {
                if (e.key === 'Enter' && e.target.value !== '') {
                    let {data: {user}} = await this.$http.get(`/main/searchUser/${e.target.value}`);
                    if (user) {
                        let canAdd = true;
                        if (user._id === this.userData._id) {
                            this.searchTips = '该用户是你自己';
                            canAdd = false;
                        } else {
                            for (let i = this.userData.friends.length - 1; i > -1; i--) {
                                if (this.userData.friends[i]._id === user._id) {
                                    this.searchTips = '该用户已是您的好友';
                                    canAdd = false;
                                    break
                                }
                            }
                        }
                        this.canAdd = canAdd;
                        this.searchUser = user;
                    } else {
                        this.searchTips = '没有搜索到相关用户';
                    }
                    this.searchShow = true;
                    e.target.value = '';
                }
            },
            sendFriReq() {
                this.socket.emit('friendReq', this.searchUser._id);
                this.hasAdd = true;
            },
            updateFriReq(res) {
                let {target, add} = res;
                for (let i = 0; i < this.userData.friendReq.length; i++) {
                    if (this.userData.friendReq[i]._id === target._id) {
                        this.userData.friendReq.splice(i, 1);
                        break
                    }
                }
                if (add) {
                    this.userData.friendReq.unshift(target);
                }
            },
            agreeFriReq(targetID) {
                this.socket.emit('agreeReq', targetID);
            },
            rejectFriReq(targetID) {
                this.socket.emit('rejectReq', targetID);
            },
            updateFriList(target) {
                for (let i = 0; i < this.userData.friendReq.length; i++) {
                    if (this.userData.friendReq[i]._id === target._id) {
                        this.userData.friendReq.splice(i, 1);
                        break
                    }
                }
                this.userData.friends.push(target);
            },
            panelHide() {
                this.searchTips = '';
                this.searchUser = null;
                this.searchShow = false;

                this.reqShow = false;
                this.hasAdd = false;
            },
            textChange(e) {
                //假input
                this.$refs.fakeInput.value = this.text;
                let height = this.$refs.fakeInput.scrollHeight;
                if (height !== this.textScrollHeight) {
                    // 如果总高度小于等于文本框最大高度便进行更新
                    if (height <= 114) {
                        if (height > this.textScrollHeight) {
                            this.inputBoxHeight += 1;
                        } else if (height < this.textScrollHeight) {
                            this.inputBoxHeight -= 1;
                        }
                        this.textScrollHeight = height;
                    } else {
                        //当超出文本框最大高度时换行需要滚动到底部
                        e.target.scrollTop = height;
                    }
                }
            },

            //点击删除按钮后执行的操作
            deleteChat() {
                this.socket.emit('delChat', {
                    oppositeID: this.chatTarget._id,
                    mID: this.messageID,
                });
            },
            //服务器返回后执行的操作
            delMessage(mID) {
                for (let i = 0; i < this.userData.currentMessages.length; i++) {
                    if (this.userData.currentMessages[i].content._id === mID) {
                        this.userData.currentMessages.splice(i, 1);
                        break
                    }
                }
                if (this.messageID === mID) {
                    this.exitChat();
                }
            },
            //加载更多信息
            checkTop(e) {
                if (this.chatMessages.length < this.totalLength && this.$refs.mList.scrollTop === 0) {
                    this.canDrag = true;
                    this.dragStartPageY = e.changedTouches[0].pageY;
                }
            },
            mListMove(e) {
                this.hasMoveList = true;
                if (!this.dragFlag && this.canDrag && e.changedTouches[0].pageY > this.dragStartPageY) {
                    this.dragFlag = true;
                    this.dragHeight = e.changedTouches[0].pageY - this.dragStartPageY;
                    setTimeout(() => {
                        this.dragFlag = false;
                    }, 20)
                }
            },
            loadMore(e) {
                //查看大图 副作用
                if (!this.hasMoveList && e.target.nodeName === 'IMG') {
                    this.viewImgSrc = e.target.src;
                    this.viewImgAlt = e.target.alt;
                    this.viewShow = true;
                    this.$refs.imgLook.init();
                } else if (this.canDrag && this.dragHeight > 50) {
                    this.dragHeight = 50;
                    this.isLoad = true;
                    this.socket.emit('loadMoreMessage', {
                        limit: this.mLimit,
                        mID: this.messageID
                    })
                }
                this.hasMoveList = false;
            },
            addMore(data) {
                if (this.messageID === data.mID) {
                    this.mLimit += 15;
                    this.chatMessages = [...data.moreMessage, ...this.chatMessages];
                }
                this.dragHeight = 0;
                this.isLoad = false;
                this.canDrag = false;
                //回到原先位置
                this.$nextTick(() => {
                    this.$refs.mList.scrollTop = this.$refs.mList.scrollHeight - this.listHeight;
                    this.listHeight = this.$refs.mList.scrollHeight;
                })
            },

            //滚动到底部
            updateMListScrollBottom() {
                this.$nextTick(() => {
                    this.$refs.mList.scrollTop =
                        this.$refs.mList.scrollHeight - this.$refs.mList.clientHeight;
                    //顺便更新高度 副作用
                    this.listHeight = this.$refs.mList.scrollHeight;
                })
            },
            //滚动到原来位置
            updateMListScroll() {
                let height = this.$refs.mList.clientHeight;
                this.$nextTick(() => {
                    this.$refs.mList.scrollTop += height - this.$refs.mList.clientHeight;
                })
            },
            toChat(e) {
                for (let user of this.userData.friends) {
                    if (user._id === e.target.dataset.uid) {
                        this.chatTarget = user;
                        break
                    }
                }
                for (let item of this.userData.currentMessages) {
                    if (item.opposite._id === e.target.dataset.uid) {
                        //清空未读
                        item.unread = 0;
                        this.socket.emit('clearUnread', item.content._id);

                        this.messageID = item.content._id;
                        this.chatMessages = [...item.content.mList];
                        this.totalLength = item.content.listLength;
                        break
                    }
                }
                this.chatShow = true;
                this.updateMListScrollBottom();
            },
            exitChat() {
                this.chatShow = false;
                this.chatTarget = {username: ''};
                this.chatMessages = [];
                this.messageID = '';
                //清除加载新信息状态
                this.mLimit = 15;
                this.dragHeight = 0;
                this.isLoad = false;
                this.canDrag = false;
                //回复对话框状态
                this.text = '';
                this.inputBoxHeight = 1;
                this.textScrollHeight = 34;
            },

            //图片查看
            closeViewer() {
                this.viewShow = false;
            },

            showEmoji() {
                this.moreShow = false;
                this.emojiShow = !this.emojiShow;
                this.updateMListScroll();
            },
            showMore() {
                this.emojiShow = false;
                this.moreShow = !this.moreShow;
                this.updateMListScroll();
            },
            addEmoji(e) {
                if (e.target.nodeName === 'I') {
                    this.text += `[${e.target.title}]`;
                }
            },

            postMessage() {
                let pre = this.text;

                let candidates = new Set();
                let key = '';
                for (let char of pre) {
                    switch (char) {
                        case '[' : key.length > 0 ? key = '' : key += char; break
                        case ']' : {
                            candidates.add(key.slice(1));
                            key = '';
                            break
                        }
                        default: key.length > 0 ? key += char : null;
                    }
                }
                for (let key of candidates) {
                    if (this.emojiList.indexOf(key) !== -1) {
                        pre = pre.replaceAll(
                            `[${key}]`,
                            `<i class="iconfont icon-${key}" title="${key}"></i>`);
                    }
                }

                pre = pre.replaceAll('\n', '<br/>');

                this.socket.emit('postMessage', {
                    text: this.text,
                    preText: pre,
                    textType: 'text',
                    targetID: this.chatTarget._id,
                    messageID: this.messageID,
                });
            },
            updateMessage(res) {
                let {mID, oppositeID, post, unread} = res;

                let data = new Date(post.time);
                post.updatedTime = data.toISOString().slice(5, 10)
                    + ' ' + data.toTimeString().slice(0, 5);

                for (let i = 0; i < this.userData.currentMessages.length; i++) {
                    let item = this.userData.currentMessages[i];
                    if (item.content._id === mID) {
                        item.content.mList.push(post);
                        item.content.listLength += 1;

                        // 为了方便直接shift掉一个数据，浪费就浪费吧
                        if (item.listLength > 15) {
                            item.content.shift();
                        }

                        if (this.chatTarget._id === oppositeID) {
                            this.chatMessages.push(post);

                            //当信息更新对象为当前聊天对象时消除input状态
                            this.text = '';
                            this.inputBoxHeight = 1;
                            this.textScrollHeight = 34;
                            this.socket.emit('clearUnread', mID);

                            //因为更新了新信息所以现在已加载的步数加一
                            this.totalLength += 1;
                            //因为更新了新信息所以现在已加载的步数加一
                            this.mLimit += 1;
                        } else if (unread !== 0) {
                            //增加未读信息条数
                            item.unread += 1;
                        }

                        //将信息推到顶上
                        this.userData.currentMessages.splice(i, 1);
                        this.userData.currentMessages.unshift(item);

                        this.updateMListScrollBottom();
                        return
                    }
                }
                let opposite = null;
                for (let user of this.userData.friends) {
                    if (user._id === oppositeID) {
                        opposite = user;
                        break;
                    }
                }
                let newMessage = {
                    opposite: opposite,
                    content: {
                        _id: mID,
                        users: [this.userData._id, oppositeID],
                        mList: [post],
                        listLength: 1,
                    },
                    unread: 0,
                }
                this.userData.currentMessages.unshift(newMessage)
                if (this.chatTarget._id === oppositeID) {
                    this.text = '';
                    this.inputBoxHeight = 1;
                    this.textScrollHeight = 34;
                    this.messageID = mID;
                    this.chatMessages = [...newMessage.content.mList];
                    this.socket.emit('clearUnread', mID);
                } else {
                    //增加未读信息条数
                    newMessage.unread = 1;
                }
                this.updateMListScrollBottom();
            },

            async postImage(e) {
                let file = e.target.files[0];
                e.target.value = '';

                if (file.type.split('/').shift() === 'image') {
                    let formData = new FormData();
                    formData.set('img', file);

                    let {data} = await this.$http.post('/chat/postImg', formData);
                    let url = [process.env.VUE_APP_SOCKET_URL || '/', data].join('');
                    let pre = `<img src="${url}" alt="${data.slice(13)}"/>`

                    this.socket.emit('postMessage', {
                        text: '[图片]',
                        preText: pre,
                        textType: 'img',
                        targetID: this.chatTarget._id,
                        messageID: this.messageID,
                    });
                }
            },

            updateAvatar({data, target}) {
                if (target === this.userData._id) {
                    this.userData.profile = data;
                } else {
                    for (let item of this.userData.friends) {
                        if (target === item._id) {
                            item.profile = data;
                            break;
                        }
                    }

                    for (let item of this.userData.currentMessages) {
                        if (item.opposite._id === target) {
                            item.opposite.profile = data;
                            break
                        }
                    }
                }
            }
        },
        mounted() {
            //消除状态 可能会造成性能问题
            let that = this;
            window.addEventListener('click', () => {
                that.emojiShow = false;
                that.moreShow = false;
                that.delChatBtn = false;
            })

            const {io} = require('socket.io-client');
            const url = process.env.VUE_APP_SOCKET_URL || '/';
            // const url = process.env.VUE_APP_DEBUGGER_SOCKET_URL || '/';
            this.socket = io(url, {
                query: {
                    token: sessionStorage.token
                }
            })

            // require('../modules/socket').call(this);
            this.socket.on('initUser', this.init)

            this.socket.on('updateOnline', this.updateOnline);

            this.socket.on('updateFriendReq', this.updateFriReq);
            this.socket.on('updateFriList', this.updateFriList);

            this.socket.on('updateMessage', this.updateMessage);
            this.socket.on('addMoreMessage', this.addMore);

            this.socket.on('delChatAccess', this.delMessage);

            this.socket.on('updateAvatar', this.updateAvatar);
        },
        beforeDestroy() {
            this.socket.disconnect();
        }
    }
</script>

<style lang="scss" scoped>
    * {
        font-size: 16px;
    }

    .container {
        width: 100vw;
        height: 100vh;
        overflow: hidden;
        padding-bottom: constant(safe-area-inset-bottom);
        padding-bottom: env(safe-area-inset-bottom);

        .move {
            width: 200vw;
            transition: transform 0.3s;

            .main,
            .chat {
                width: 100vw;
                height: 100vh;
                overflow: hidden;
            }

            .main {
                .header {
                    width: 100%;
                    height: 70px;
                    padding: 5px 10px;
                    box-sizing: border-box;
                    flex-shrink: 0;

                    .profile {
                        width: 40px;
                        height: 40px;
                        border-radius: 50%;
                        flex-shrink: 0;
                        background-color: #aaa;
                    }

                    .userData {
                        padding: 5px 8px;
                        box-sizing: border-box;
                        height: 100%;
                        overflow: hidden;

                        .name {
                            width: 100%;
                            font-size: 19px;
                            line-height: 25px;
                            overflow: hidden;
                            text-overflow: ellipsis;
                            white-space: nowrap;
                        }

                        .signature {
                            width: 100%;
                            padding-right: 20px;
                            box-sizing: border-box;
                            font-size: 12px;
                            overflow: hidden;
                            text-overflow: ellipsis;
                            white-space: nowrap;
                            color: #777;
                        }
                    }

                    .friendReq {
                        width: 20px;
                        height: 20px;
                        flex-shrink: 0;

                        .notification {
                            position: absolute;
                            bottom: -2px;
                            right: -2px;
                            width: 8px;
                            height: 8px;
                            border-radius: 50%;
                            background-color: #DD4A68;
                        }
                    }
                }

                .search {
                    width: 100%;
                    height: 35px;
                    margin-bottom: 10px;
                    padding: 0 10px;
                    box-sizing: border-box;
                    flex-shrink: 0;

                    input {
                        height: 100%;
                        width: 100%;
                        padding: 0 10px;
                        box-sizing: border-box;
                        border: 0;
                        border-radius: 10px;
                        outline-style: none;
                        background-color: #f5f5f5;
                        color: #999;
                    }

                    input::placeholder {
                        color: #999;
                    }

                    .return {
                        position: absolute;
                        top: 0;
                        left: 0;
                        width: 100%;
                        height: 100%;
                        background-color: white;

                        .box {
                            width: 70px;
                            height: 100%;

                            .iconfont {
                                margin-left: 5px;
                                padding: 0 5px;
                                transform: rotate(90deg);
                            }
                        }
                    }
                }

                .content {
                    width: 200vw;
                    overflow: hidden;
                    transition: transform 0.3s;

                    .currentMessage,
                    .friends {
                        width: 100vw;
                        height: 100%;
                        box-sizing: border-box;
                        overflow: scroll;

                        .clickTarget {
                            position: absolute;
                            top: 0;
                            left: 0;
                            width: 100%;
                            height: 100%;
                        }
                    }

                    .currentMessage {
                        .hidden {
                            overflow: hidden;
                        }

                        .notice {
                            font-size: 15px;
                            padding: 8px 15px;
                        }

                        .item {
                            width: 100%;
                            height: 75px;
                            box-sizing: border-box;
                            padding: 0 10px;

                            .profile {
                                width: 50px;
                                height: 50px;
                                flex-shrink: 0;
                                border-radius: 50%;
                                background-color: #aaa;
                            }

                            .data {
                                padding-left: 8px;
                                box-sizing: border-box;
                                overflow: hidden;

                                .name {
                                    flex: 1;
                                    overflow: hidden;
                                    text-overflow: ellipsis;
                                    white-space: nowrap;
                                }

                                .time {
                                    font-size: 14px;
                                    color: #ccc;
                                    text-align: center;
                                    flex-shrink: 0;
                                }

                                .massage {
                                    margin-top: 4px;

                                    p {
                                        padding-right: 20px;
                                        font-size: 14px;
                                        color: #999;
                                        overflow: hidden;
                                        text-overflow: ellipsis;
                                        white-space: nowrap;
                                    }

                                    .notification {
                                        width: 30px;
                                        height: 20px;
                                        flex-shrink: 0;
                                        border-radius: 10px;
                                        text-align: center;
                                        font-size: 12px;
                                        line-height: 20px;
                                        color: white;
                                        background-color: #DD4A68;
                                    }
                                }
                            }
                        }

                        .delete {
                            position: absolute;
                            top: 0;
                            right: -100px;
                            width: 100px;
                            height: 100%;
                            color: white;
                            background-color: #DD4A68;
                        }
                    }

                    .friends {
                        padding-top: 4px;

                        .group {
                            width: 100%;
                            height: 35px;
                            padding: 0 8px;
                            box-sizing: border-box;

                            .name,
                            .num {
                                font-size: 15px;
                            }

                            .name {
                                padding-left: 4px;
                            }

                            .num {
                                color: #999;
                                padding-right: 4px;
                            }
                        }

                        .item {
                            width: 100%;
                            padding: 8px 10px;
                            box-sizing: border-box;

                            .profile {
                                width: 50px;
                                height: 50px;
                                border-radius: 50%;
                                flex-shrink: 0;
                                background-color: #aaa;
                            }

                            .userData {
                                padding-left: 6px;
                                box-sizing: border-box;
                                overflow: hidden;

                                .name {
                                    overflow: hidden;
                                    text-overflow: ellipsis;
                                    white-space: nowrap;
                                }

                                .signature {
                                    margin-top: 4px;
                                    padding-right: 15px;
                                    font-size: 14px;
                                    color: #999;
                                    overflow: hidden;
                                    text-overflow: ellipsis;
                                    white-space: nowrap;
                                }
                            }
                        }
                    }

                    .searchPanel,
                    .reqPanel {
                        position: absolute;
                        top: 0;
                        left: 0;
                        width: 100vw;
                        height: 100%;
                        background-color: white;

                        .tips {
                            width: 100%;
                            margin-bottom: 15px;
                            padding: 0 10px;
                            box-sizing: border-box;
                            color: #999;
                        }

                        .returnValue {
                            width: 100%;
                            padding: 0 10px;
                            box-sizing: border-box;

                            .profile {
                                width: 50px;
                                height: 50px;
                                flex-shrink: 0;
                                border-radius: 50%;
                                background-color: #aaa;
                            }

                            .data {
                                padding-left: 8px;
                                box-sizing: border-box;
                                overflow: hidden;

                                .name {
                                    margin-top: 4px;
                                    overflow: hidden;
                                    text-overflow: ellipsis;
                                    white-space: nowrap;
                                }

                                .signature {
                                    margin-top: 4px;
                                    padding-right: 20px;
                                    font-size: 14px;
                                    color: #999;
                                    overflow: hidden;
                                    text-overflow: ellipsis;
                                    white-space: nowrap;
                                }
                            }

                            a {
                                width: 50px;
                                text-align: center;
                                line-height: 50px;
                            }
                        }
                    }

                    .reqPanel {
                        padding-top: 5px;
                    }
                }

                .nav {
                    width: 100%;
                    height: 40px;
                    border-top: 1px solid #e6e6e6;
                    flex-shrink: 0;

                    div {
                        display: flex;
                        width: 50%;
                        height: 100%;
                        justify-content: center;
                        align-items: center;
                    }
                }
            }

            .chat {
                background-color: #f5f5f5;

                .header {
                    width: 100%;
                    height: 50px;
                    padding: 0 8px;
                    box-sizing: border-box;
                    flex-shrink: 0;

                    .back,
                    .more {
                        width: 23px;
                        height: 23px;
                        flex-shrink: 0;

                        .iconfont {
                            line-height: 25px;
                            font-size: 23px;

                            &.icon-more {
                                font-weight: bolder;
                            }
                        }
                    }

                    .name {
                        padding: 0 10px;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                        font-size: 17px;
                    }

                    .back {
                        transform: rotate(90deg);
                    }

                    .delete {
                        position: absolute;
                        top: 30px;
                        right: 0;
                        width: 100px;
                        height: 45px;
                        line-height: 45px;
                        border-radius: 6px;
                        text-align: center;
                        background: white;
                        z-index: 100;
                    }
                }

                .content {
                    padding: 5px 12px;
                    overflow: scroll;

                    .loadingPanel {
                        position: absolute;
                        top: -40px;
                        left: 0;
                        width: 100%;
                        height: 40px;
                        text-align: center;

                        @keyframes load {
                            from {transform: rotate(0)}
                            to {transform: rotate(360deg)}
                        }

                        .loadBox {
                            width: 30px;
                            height: 30px;

                            &.play {
                                animation: load linear 1s infinite;
                            }

                            .iconfont {
                                font-size: 24px;
                            }
                        }
                    }

                    li {
                        margin-bottom: 25px;
                    }

                    li:last-child {
                        margin-bottom: 12px;
                    }

                    .profile {
                        width: 40px;
                        height: 40px;
                        border-radius: 50%;
                        background-color: #aaa;
                    }

                    .info {
                        padding-left: 8px;

                        .name {
                            margin-bottom: 6px;
                            padding-left: 6px;
                            font-size: 14px;
                            color: #999;
                        }

                        .message {
                            position: relative;
                            max-width: 70vw;
                            box-sizing: border-box;
                            padding: 10px 12px;
                            border-radius: 8px;
                            white-space: pre-wrap;
                            word-break: break-all;
                            overflow-wrap: break-word;
                            background-color: white;
                            line-height: 22px;

                            &.img {
                                padding: 0;
                                display: flex;

                                ::v-deep img {
                                    max-width: 70vw;
                                    max-height: 350px;
                                    border-radius: 8px;
                                }
                            }

                            ::v-deep .iconfont {
                                padding: 0 2px;
                                font-size: 25px;
                                line-height: 25px;
                            }
                        }

                        /*.message::before {
                            content: '';
                            display: block;
                            position: absolute;
                            width: 0;
                            height: 0;
                            top: 10px;
                            left: -10px;
                            border-top: 10px solid white;
                            border-left: 10px solid transparent;
                        }*/

                    }

                    .userSite {
                        flex-direction: row-reverse;

                        .info {
                            padding-left: 0;
                            padding-right: 8px;

                            .name {
                                padding-left: 0;
                                padding-right: 6px;
                                text-align: right;
                            }

                            .message {
                                color: white;
                                background-color: #009aff;
                            }
                        }
                    }
                }

                label {
                    font-size: 0;
                }

                .input {
                    width: 100%;
                    padding: 0 10px;
                    box-sizing: border-box;
                    line-height: 20px;
                    flex-shrink: 0;
                    background-color: white;

                    $highs: (
                        1: 50,
                        2: 70,
                        3: 90,
                        4: 110,
                        5: 130,
                    );

                    @each $key, $size in $highs {
                        &.h#{$key} {
                            height: #{$size}px;
                        }
                    }

                    .text {
                        width: 100%;
                        height: 100%;
                        padding: 8px 1px;
                        box-sizing: border-box;

                        textarea {
                            width: 100%;
                            height: 100%;
                            padding: 7px 10px;
                            box-sizing: border-box;
                            outline: none;
                            border: none;
                            border-radius: 4px;
                            background-color: #f5f5f5;
                            resize: none;

                            &.fakeInput {
                                width: 100%;
                                height: 0;
                                opacity: 0;
                            }
                        }
                    }

                    .other {
                        margin-left: 4px;
                        height: 50px;
                        flex-shrink: 0;

                        .emoji,
                        .more, {
                            margin-left: 6px;

                            .iconfont {
                                line-height: 28px;
                                font-size: 28px;
                                color: rgb(104 110 121);
                            }
                        }

                        .send {
                            display: block;
                            width: 54px;
                            height: 30px;
                            margin-left: 6px;
                            line-height: 30px;
                            border-radius: 5px;
                            font-size: 14px;
                            text-align: center;
                            color: white;
                            background-color: #009aff;
                        }
                    }
                }

                .moreBox {
                    .emojiList,
                    .more {
                        width: 100%;
                        height: 200px;
                        overflow: scroll;
                        box-sizing: border-box;
                        flex-wrap: wrap;
                    }

                    .emojiList {
                        div {
                            display: flex;
                            width: 12.5vw;
                            height: 12vw;
                            justify-content: center;
                            align-items: center;

                            .iconfont {
                                line-height: 7vw;
                                font-size: 7vw;
                                color: rgb(104 110 121);
                            }
                        }
                    }

                    .more {
                        padding: 20px 4vw;

                        .box {
                            width: 23vw;
                            margin-bottom: 15px;

                            .iconfont {
                                width: 16vw;
                                height: 16vw;
                                border-radius: 10px;
                                font-size: 26px;
                                background-color: white;
                            }

                            input {
                                position: absolute;
                                top: 0;
                                left: 0;
                                width: 100%;
                                height: 100%;
                                font-size: 0;
                                opacity: 0;
                            }
                        }
                    }
                }

                .pictureView {
                    position: absolute;
                    top: 0;
                    left: 0;
                    width: 100vw;
                    height: 100vh;
                    background-color: rgba(0, 0, 0, .3);
                    overflow: scroll;

                    img {
                        max-width: 100vw;
                        max-height: 100vh;
                    }
                }
            }
        }
    }
</style>